package com.int_tech.facility.controller;

import com.int_tech.utils.GetUUID;
import com.int_tech.utils.Result;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * Created by Administrator on 2017/10/16.
 */
@Controller
@RequestMapping("file")
public class FileController {

    //测试
    @RequestMapping("file")
    public String file(){
        return "/facility/index";
    }
    //测试
    @RequestMapping("file2")
    public String file1(){
        return "/facility/index2";
    }

//    private static final Logger logger = LoggerFactory.getLogger(FileController.class);
    //文件上传相关代码
    @RequestMapping(value = "upload")
    @ResponseBody
    public Result upload(@RequestParam("fileName") MultipartFile file) {
        if (file.isEmpty()) {
            return Result.build(201,"路径为空");
        }
        // 获取文件名
        String fileName = file.getOriginalFilename();
//        logger.info("上传的文件名为：" + fileName);
        // 获取文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
//        logger.info("上传的后缀名为：" + suffixName);
        // 文件上传后的路径
        String filePath = "D:\\test\\";
        // 解决中文问题，liunx下中文路径，图片显示问题
         fileName = GetUUID.getId() + suffixName;
        File dest = new File(filePath + fileName);
        // 检测是否存在目录
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
            return Result.ok(dest);
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Result.build(500,"上传失败");
    }
}
